package OrderService

import (
	"context"
	"database/sql"
	"gdshop-back-end-go/admin-api/app/response/OrderResp"
	OrderResp2 "gdshop-back-end-go/client-api/app/response/OrderResp"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/entity"
	"gdshop-back-end-go/common/request/BaseReq"
	"gdshop-back-end-go/common/response"
	"gdshop-back-end-go/common/tools"
	"gdshop-back-end-go/service-common/BaseService"
	"gdshop-back-end-go/service-order/FenxiaoService"

	"github.com/gogf/gf/container/garray"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"strings"
)

func getPayLogsPaymentName(paymentMethod string) string {
	switch paymentMethod {
	case "1":
		return "余额支付"
	case "2":
		return "后台付款"
	case "3":
		return "微信支付"
	case "4":
		return "支付宝"
	}

	return "未知"
}

func getPayLogs(ctx context.Context, orderId string) g.List {
	all, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "order_pay_log").Where(
		"order_id",
		orderId).Fields("payment_method,money,create_at").Order("create_at DESC").All()
	if err != nil {
		return nil
	}

	allList := all.List()

	for _, item := range allList {
		item["payment_method_name"] = getPayLogsPaymentName(gconv.String(item["payment_method"]))
	}

	return allList
}
func getPayLogsByOrderIds(ctx context.Context, orderIds []int) map[int][]*OrderResp.PayLogs {
	if len(orderIds) < 1 {
		return map[int][]*OrderResp.PayLogs{}
	}
	resList := []*OrderResp.PayLogs{}
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "order_pay_log").Where(
		"order_id IN (?)",
		gconv.SliceInt(orderIds)).Fields("order_id,payment_method,money,create_at").Order("create_at DESC").Structs(&resList)
	if err != nil {
		return nil
	}

	for _, item := range resList {
		item.PaymentMethodName = getPayLogsPaymentName(gconv.String(item.PaymentMethod))
	}

	fanhuiMap := map[int][]*OrderResp.PayLogs{}

	for _, item := range resList {
		fanhuiMap[item.OrderId] = append(fanhuiMap[item.OrderId], item)
	}

	return fanhuiMap
}

// 获取子订单信息
func getOrderSubListByOrderId(ctx context.Context, orderId string) g.List {
	all, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "order_sub").Where(
		"order_id",
		orderId).All()
	if err != nil {
		return nil
	}

	/*allList := all.List()

	for _,item := range allList{
		item["payment_method_name"] = getPayLogsPaymentName(gconv.String(item["payment_method"]))
	}*/

	return all.List()
}

// 获取子订单信息并且拉取物流信息
func getOrderSubAndExpressListByOrderId(ctx context.Context, orderId string) []*entity.OrderSub {
	var subList []*entity.OrderSub
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "order_sub").As("os").Where(
		"os.order_id",
		orderId).Fields("os.*,oe.express_com,oe.express,oe.express_sn").LeftJoin("order_express oe", "oe.order_sub_id = os.id AND oe.delete_at < 1").Structs(&subList)
	if err != nil {
		return nil
	}
	return subList
}

func GetOrderSubAndExpressListByOrderIds(ctx context.Context, orderIds []int) map[int][]*entity.OrderSub {
	if len(orderIds) < 1 {
		return map[int][]*entity.OrderSub{}
	}
	var subList []*entity.OrderSub
	fields := "os.*,oe.express_com,oe.express,oe.express_sn,osc.discount AS coupon_discount,osa.discount AS activity_discount"
	fields += ",ot.discount AS tuan_discount"
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "order_sub").As("os").Where(
		"os.order_id IN (?)",
		gconv.SliceInt(orderIds)).Fields(fields).
		LeftJoin("order_express oe", "oe.order_sub_id = os.id AND oe.delete_at < 1").
		LeftJoin("order_sub_coupon osc", "osc.order_sub_id = os.id").
		LeftJoin("order_sub_activity osa", "osa.order_sub_id = os.id").
		LeftJoin("order_tuan ot", "ot.order_sub_id = os.id").
		Structs(&subList)
	if err != nil {
		return nil
	}

	fanhuiMap := map[int][]*entity.OrderSub{}

	for _, item := range subList {
		fanhuiMap[item.OrderId] = append(fanhuiMap[item.OrderId], item)
	}

	return fanhuiMap
}

func GetOrderSubAndFenxiaoListByOrderIds(ctx context.Context, orderIds []int) map[int][]*entity.OrderSub {
	if len(orderIds) < 1 {
		return map[int][]*entity.OrderSub{}
	}
	fields := []string{}
	fields = append(fields, "os.*")
	fields = append(fields, FenxiaoService.GetFenxiaoOrderLevelFields(3, "fo.")...)
	fields = append(fields, "fo.paid AS fo_paid,fo.status AS fo_status,fo.settle_accounts_at AS fo_settle_accounts_at")
	fields = append(fields, "osc.discount AS coupon_discount,osa.discount AS activity_discount")

	var subList []*entity.OrderSub
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "order_sub").As("os").Where(
		"os.order_id IN (?)",
		gconv.SliceInt(orderIds)).Fields(fields).
		LeftJoin("fenxiao_order fo", "fo.order_sub_id = os.id AND fo.delete_at < 1").
		LeftJoin("order_sub_coupon osc", "osc.order_sub_id = os.id").
		LeftJoin("order_sub_activity osa", "osa.order_sub_id = os.id").
		Structs(&subList)
	if err != nil {
		return nil
	}

	// 先取出分销商ID，方便批量查出名称
	fuIds := garray.NewIntArray(true)
	for _, item := range subList {
		if !fuIds.Contains(item.OneFenxiaoUserId) && item.OneFenxiaoUserId > 0 {
			fuIds.Append(item.OneFenxiaoUserId)
		}
		if !fuIds.Contains(item.TwoFenxiaoUserId) && item.TwoFenxiaoUserId > 0 {
			fuIds.Append(item.TwoFenxiaoUserId)
		}
		if !fuIds.Contains(item.ThreeFenxiaoUserId) && item.ThreeFenxiaoUserId > 0 {
			fuIds.Append(item.ThreeFenxiaoUserId)
		}
	}
	var fuList []*entity.FenxiaoUser
	err = toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "fenxiao_user").Fields(
		"id,name").Where("id IN (?)", fuIds.Slice()).Scan(&fuList)
	if err != nil {
		return map[int][]*entity.OrderSub{}
	}

	fuArrayMap := map[int]string{}
	for _, item := range fuList {
		fuArrayMap[item.Id] = item.Name
	}

	for _, item := range subList {
		if item.OneFenxiaoUserId > 0 {
			item.OneFenxiaoUserName = fuArrayMap[item.OneFenxiaoUserId]
		}
		if item.TwoFenxiaoUserId > 0 {
			item.TwoFenxiaoUserName = fuArrayMap[item.TwoFenxiaoUserId]
		}
		if item.ThreeFenxiaoUserId > 0 {
			item.ThreeFenxiaoUserName = fuArrayMap[item.ThreeFenxiaoUserId]
		}
	}

	fanhuiMap := map[int][]*entity.OrderSub{}

	for _, item := range subList {
		fanhuiMap[item.OrderId] = append(fanhuiMap[item.OrderId], item)
	}

	return fanhuiMap
}

// 获取价格详情
func getOrderPriceTableByOrderModel(orderMap g.Map) g.List {
	//fmt.Println("getOrderPriceTableByOrderModel " , orderMap)
	resultList := []g.Map{}
	resultList = append(resultList, g.Map{
		"text":     "商品合计",
		"is_color": 0,
		"value":    orderMap["original_total_price"],
	})

	totalPriceChange := gconv.Float64(orderMap["total_price_change"])
	if totalPriceChange != 0 {
		resultList = append(resultList, g.Map{
			"text":     "卖家改价",
			"is_color": 1,
			"value":    totalPriceChange,
		})
	}

	resultList = append(resultList, g.Map{
		"text":     "原运费",
		"is_color": 0,
		"value":    orderMap["original_dispatch_price"],
	})
	dispatchPriceChange := gconv.Float64(orderMap["dispatch_price_change"])
	if dispatchPriceChange != 0 {
		resultList = append(resultList, g.Map{
			"text":     "卖家改运费",
			"is_color": 1,
			"value":    dispatchPriceChange,
		})
	}

	totalDiscount := getTotalDiscount(orderMap)
	if totalDiscount != nil {
		if totalDiscount.Activity > 0 {
			resultList = append(resultList, g.Map{
				"text":     "活动",
				"is_color": 1,
				"value":    -totalDiscount.Activity,
			})
		}
		if totalDiscount.Coupon > 0 {
			resultList = append(resultList, g.Map{
				"text":     "优惠券",
				"is_color": 1,
				"value":    -totalDiscount.Coupon,
			})
		}
		if totalDiscount.Tuan > 0 {
			resultList = append(resultList, g.Map{
				"text":     "团购",
				"is_color": 1,
				"value":    -totalDiscount.Tuan,
			})
		}
	}

	resultList = append(resultList, g.Map{
		"text":     "应收款",
		"is_color": 0,
		"value":    orderMap["total_price"],
	})

	return resultList
}

func getTotalDiscount(orderMap g.Map) *OrderResp2.TotalDiscount {
	tmps, ok := orderMap["subs"]
	if ok {
		subs := tmps.([]*entity.OrderSub)
		totalCouponDiscount := 0
		totalActivityDiscount := 0
		totalTuanDiscount := 0

		for _, item := range subs {
			totalCouponDiscount += item.CouponDiscount
			totalActivityDiscount += item.ActivityDiscount
			totalTuanDiscount += item.TuanDiscount
		}

		return &OrderResp2.TotalDiscount{
			Activity: totalActivityDiscount,
			Coupon:   totalCouponDiscount,
			Tuan:     totalTuanDiscount,
		}
	}
	return nil
}

// 是否显示 优惠详情 按钮
func getIsDiscountBtnByOrderModel(orderMap g.Map) int {
	discountModel := getTotalDiscount(orderMap)
	if discountModel == nil {
		return 0
	}
	if discountModel.Activity == 0 && discountModel.Coupon == 0 && discountModel.Tuan == 0 {
		return 0
	}
	return 1
}

func getOrderIsModfiyPriceByOrderModel(orderMap g.Map) int {
	resultInt := 0

	if gconv.Int(orderMap["total_price_change"]) != 0 {
		resultInt++
	}

	if gconv.Int(orderMap["dispatch_price_change"]) != 0 {
		resultInt++
	}

	if resultInt > 0 {
		return 1
	} else {
		return 0
	}
}

// 判断订单是否可以取消备货，返回 0 是不可以取消备货
func getOrderIsCancelGoodsByOrderSubList(data []*entity.OrderSub) int {
	fanhui := 1
	for _, item := range data {
		if item.Status == 4 {
			fanhui = 0
		}
	}

	return fanhui
}

func getPageListTypeToStatus(listType int) int {
	switch listType {
	case 1, 2, 3, 4, 5, 99:
		return listType
	case 6:
		return 0
	}

	return 0
}

func Page(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	condition := g.Map{}
	obj := toolsDb.GetUnSafaTable(ctx, req.TableName)
	countObj := toolsDb.GetUnSafaTable(ctx, req.TableName)
	// 默认全部表别名先设置为 a
	asName := "a"
	// 处理查询的列
	selectFields := ""
	defaultSelectFields := strings.Split(obj.GetFieldsStr(), ",")

	pageQueryOp := req.PageQueryOp
	if pageQueryOp != nil {
		if pageQueryOp.AsName != "" {
			asName = pageQueryOp.AsName
		}
	}
	// 有设置表别名
	obj.As(asName)
	countObj.As(asName)
	// 获取查询条件
	BaseService.GetCondition(r, condition, pageQueryOp, asName)

	listType := r.GetInt("list_type", 0)
	if listType > 0 {
		condition["o.status"] = getPageListTypeToStatus(listType)
	}

	obj.Where(
		condition,
	)
	countObj.Where(
		condition,
	)

	if pageQueryOp != nil {
		if len(pageQueryOp.SelectFields) > 0 {
			// 设置了 select 的
			selectFields = strings.Join(pageQueryOp.SelectFields, ",")
		}
		if pageQueryOp.OrderBy != "" {
			obj.Order(pageQueryOp.OrderBy)
		}
	}
	// 设置 select
	if selectFields != "" {
		obj.Fields(selectFields)
	} else {
		for k, v := range defaultSelectFields {
			defaultSelectFields[k] = asName + "." + v
		}
		obj.Fields(strings.Join(defaultSelectFields, ","))
	}
	// 处理查询里 --- end ---
	// 设置 删除时间
	obj.Where(asName + ".delete_at < 1")
	countObj.Fields("1").Where(asName + ".delete_at < 1")

	if pageQueryOp != nil {
		for _, item := range pageQueryOp.LeftJoin {
			obj.LeftJoin(item.TableInfo, item.Condition)
		}
	}
	count, countErr := countObj.Count()
	if countErr != nil {
		return response.FailByRequestMessage(nil, countErr.Error())
	}
	res, err := obj.Page(req.Page, req.PageSize).All()
	if err != nil {
		if err != sql.ErrNoRows {
			// 非 结果为空
			return response.FailByRequestMessage(nil, err.Error())
		}
	}

	// 获取其他数据
	resList := res.List()
	var orderIds []int
	for _, item := range resList {
		orderIds = append(orderIds, gconv.Int(item["id"]))
	}

	payLogs := getPayLogsByOrderIds(ctx, orderIds)
	subList := GetOrderSubAndExpressListByOrderIds(ctx, orderIds)
	for _, item := range resList {
		orderId := gconv.Int(item["id"])
		item["pay_logs"] = payLogs[orderId]
		item["subs"] = subList[orderId]
		item["is_cancel_goods"] = getOrderIsCancelGoodsByOrderSubList(subList[orderId])
		item["price_table"] = getOrderPriceTableByOrderModel(item)
		item["is_discount_btn"] = getIsDiscountBtnByOrderModel(item)
		item["is_modfiy_price"] = getOrderIsModfiyPriceByOrderModel(item)
		if len(gconv.String(item["store_name"])) < 1 {
			item["store_name"] = "自营"
		}
	}

	return response.SuccessByRequestMessageData(nil, "获取成功",
		g.Map{
			"list":       resList,
			"pagination": tools.GetPageInfo(count, req.Page, req.PageSize),
		})
}
